<template>
  <a-card :bordered="false">
    <a-modal
      :visible="visible"
      @cancel="
        () => {
          this.visible = false
        }
      "
    >
      <a-upload
        name="file"
        :multiple="false"
        :showUploadList="true"
        :action="$rootUrl + '/MaterialManagement/TaxMaterials/TaxMaterialsImport'"
        :headers="headers"
        @change="handleChange"
        style="display: inline-block"
        accept=".xlsx,.xls"
        class="upload-list-inline"
      >
        <a-button type="primary">
          <a-icon type="upload" />
          上传Excel数据
        </a-button>
      </a-upload>
      <template slot="footer">
        <a-button
          @click="
            () => {
              this.visible = false
            }
          "
          >关闭</a-button
        >
      </template>
    </a-modal>
    <div class="table-operator" style="display: flex; justify-content: space-between">
      <div>
        <a-button type="primary" icon="download" @click="downloadTemplate">下载模板</a-button>
        <a-button type="primary" icon="upload" @click="handleImport()">导入</a-button>
        <a-button v-if="hasPerm('TaxMaterials.Add')" type="primary" icon="plus" @click="handleAdd()">新增</a-button>
      </div>

      <a-form layout="inline">
        <a-row :gutter="10">
          <a-col :md="24" :sm="24">
            <a-form-item label="查询类别">
              <a-select allowClear v-model="queryParam.condition">
                <a-select-option key="TM_Name">物料名称</a-select-option>
                <a-select-option key="TM_AbbCode">物料简码</a-select-option>
                <a-select-option key="TM_TaxCode">税务编码</a-select-option>
                <a-select-option key="TM_Code">物料编码</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item>
              <a-input v-model="queryParam.keyword" placeholder="关键字" @keydown.enter="getDataList" />
            </a-form-item>
            <a-form-item>
              <a-button
                type="primary"
                @click="
                  () => {
                    this.pagination.current = 1
                    this.getDataList()
                  }
                "
                >查询
              </a-button>
              <a-button
                style="margin-left: 8px"
                @click="
                  queryParam = { condition: 'TM_Name' }
                  getDataList()
                "
                >重置
              </a-button>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <div class="table-page-search-wrapper"></div>

    <a-table
      ref="table"
      :scroll="{ y: 'calc(100vh - 330px)' }"
      :columns="columns"
      :rowKey="(row) => row.Id"
      :dataSource="data"
      :pagination="pagination"
      :loading="loading"
      @change="handleTableChange"
      :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      :bordered="true"
      size="small"
    >
      <span slot="CreateTime" slot-scope="CreateTime">{{ timeFormat(CreateTime, 'YYYY-MM-DD HH:mm') }}</span>
      <span slot="action" slot-scope="text, record">
        <template>
          <a v-if="hasPerm('TaxMaterials.Edit')" @click="handleEdit(record.Id)" style="margin-right: 8px">编辑</a>
          <a v-if="hasPerm('TaxMaterials.Delete')" @click="handleDelete([record.Id])">删除</a>
        </template>
      </span>
    </a-table>

    <edit-form ref="editForm" :parentObj="this"></edit-form>
  </a-card>
</template>

<script>
import Token from '@/utils/cache/TokenCache'
import EditForm from './EditForm'
import { exportXlsxFile } from '@/utils/plugin/exportFile-xlsx'

const columns = [
  { title: '税务编码', dataIndex: 'TM_TaxCode' },
  { title: '物料简码', dataIndex: 'TM_AbbCode', width: '100px', align: 'center' },
  { title: '物料编码', dataIndex: 'TM_Code' },
  { title: '物料名称', dataIndex: 'TM_Name' },
  { title: '物料规格', dataIndex: 'TM_Specs', width: '100px', align: 'center' },
  { title: '计量单位', dataIndex: 'TM_Unit', width: '100px', align: 'center' },
  { title: '物料单价', dataIndex: 'TM_UnitPrice', align: 'right' },
  { title: '是否含税', dataIndex: 'TM_IsTax', width: '80px', align: 'center' },
  { title: '税率', dataIndex: 'TM_TaxRate', width: '80px', align: 'right' },
  { title: '操作', dataIndex: 'action', align: 'center', scopedSlots: { customRender: 'action' }, width: '100px' },
]

export default {
  components: {
    EditForm,
  },
  mounted() {
    this.$nextTick(() => {
      // 页面渲染完成后的回调
      this.tableHeight = this.getTableHeight(true) + 24
    })
    this.getDataList()
  },
  data() {
    return {
      tableHeight: 570, // 表格高度
      data: [],
      pagination: {
        current: 1,
        pageSize: 20,
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
        pageSizeOptions: ['20', '30', '40', '50', '100'], // 设置pageSize的可选值，页面可以通过下拉框进行选择
        showSizeChanger: true,
      },
      filters: {},
      sorter: { field: 'CreateTime', order: 'desc' },
      loading: false,
      columns,
      queryParam: {
        condition: 'TM_Name',
      },
      selectedRowKeys: [],
      visible: false,
      headers: {
        authorization: 'Bearer ' + Token.getToken(),
      },
    }
  },
  methods: {
    handleEdit(id) {
      this.$refs.editForm.openForm(id, '编辑税务目录')
    },
    handleTableChange(pagination, filters, sorter) {
      this.pagination = { ...pagination }
      this.filters = { ...filters }
      this.getDataList()
    },
    getDataList() {
      this.selectedRowKeys = []
      this.loading = true
      this.$http
        .post('MaterialManagement/TaxMaterials/GetDataList', {
          PageIndex: this.pagination.current,
          PageRows: this.pagination.pageSize,
          SortField: this.sorter.field || 'Id',
          SortType: this.sorter.order,
          Search: this.queryParam,
          ...this.filters,
        })
        .then((resJson) => {
          this.loading = false
          this.data = resJson.Data
          this.data.forEach((item) => {
            item.TM_UnitPrice = this.$options.filters.NumberFormatss(item.TM_UnitPrice)
          })
          // 0否1是
          this.data.forEach((item) => {
            item.TM_IsTax = item.TM_IsTax ? '是' : '否'
          })
          if (this.data) {
            const pagination = { ...this.pagination }
            pagination.total = resJson.Total
            this.pagination = pagination
          }
        })
    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    hasSelected() {
      return this.selectedRowKeys.length > 0
    },
    // 导入
    handleImport() {
      this.visible = true
    },
    //新增
    handleAdd() {
      this.$refs.editForm.openForm(null, '新增税务目录')
    },
    downloadTemplate() {
      this.$http
        .post('/MaterialManagement/TaxMaterials/ExportToExcel', null, { responseType: 'blob' })
        .then((res) => {
          const url = URL.createObjectURL(res)
          const fileName = '税务目录模板'
          const aTag = document.createElement('a')
          aTag.download = fileName
          aTag.href = url
          aTag.click()
          URL.revokeObjectURL(aTag.href)
        })
        .catch((err) => {
          this.$message.error(err)
        })
    },
    // 导入文件类型
    handleChange(info) {
      // if (info.file.status !== 'uploading') {
      // }
      if (info.file.status === 'done') {
        if (info.file.response.Success === false) {
          this.$message.error(`${info.file.name}文件,${info.file.response.Msg},请检查文件内容！ `)
        } else {
          let data = info.file.response.Data
          if (data.Exists && data.Exists.length) {
            this.$message.warning(`${data.ReturnValue}，重复数据${data.Exists.length}条`)
            // 导出重复文件
            this.exportMaterialFile(data.Exists, info.file.name)
          } else {
            this.$message.success(`${data.ReturnValue}`)
          }
          this.getDataList()
        }
        this.visible = false
      } else if (info.file.status === 'error') {
        this.$message.error(`${info.file.name} 文件上传失败！`)
      }
    },
    handleDelete(ids) {
      var thisObj = this
      this.$confirm('确认删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        return new Promise((resolve, reject) => {
          thisObj.$http.post('/MaterialManagement/TaxMaterials/DeleteData', ids).then((resJson) => {
            resolve()

            if (resJson.Success) {
              thisObj.$message.success('操作成功!')

              thisObj.getDataList()
            } else {
              thisObj.$message.error(resJson.Msg)
            }
          })
        })
      })
    },
    // 导出重复物料文件
    exportMaterialFile(textList, fileName) {
      console.log(textList, fileName, 'test')
      let name = fileName.split('.')[0]
      let newFileName = `${name}-物料重复统计`
      let data = [['物料编码']]
      textList.forEach((item) => {
        data.push([item])
      })

      exportXlsxFile(data, newFileName)
    },
  },
}
</script>

<style lang="less" scoped>
/deep/ .ant-card-body {
  padding-bottom: 0px;
}
</style>
